package com.yequan.exe.core.handler;

import com.yequan.exe.core.LogOutListener;
import com.yequan.exe.core.ProcessExecutor;
import com.yequan.exe.core.ExeExecutorExtListener;
import com.yequan.exe.core.filter.LogFilter;
import com.yequan.exe.service.CalcDbService;
import com.yequan.mqservice.ResultMsgProducerService;
import com.yequan.pojo.CalcData;

/**
 * @author yq
 * @date 2020/09/29
 */
public abstract class AbstractExeHandler implements ExeHandler, LogOutListener, LogFilter {

    private CalcDbService calcDbService;

    private ResultMsgProducerService resultMsgProducerService;

    /**
     * 准备cmd命令
     *
     * @param calcData
     */
    @Override
    public abstract void combineCommand(CalcData calcData);

    @Override
    public void beforeExecute(CalcData calcData) {
        calcDbService.saveCalc();
    }

    @Override
    public int execute(CalcData calcData) {
        System.out.println("接收的命令为：" + calcData.getExeInfo().getCommand());
        if (null == calcData.getExeInfo().getCommand()) {
            System.out.println("命令为空，无法执行");
            return -1;
        }
        ProcessExecutor processExecutor = new ProcessExecutor(calcData, this);
        return processExecutor.execute();
    }

    @Override
    public void afterExecute(CalcData calcData, int result) {
        calcDbService.updateCalc();
    }

    @Override
    public void doSendLog(String line) {
        if (!preLogSendFilter(line) && null != line) {
            //通过mq将消息发送出去
//            System.out.println("logOut ======> " + line);
            resultMsgProducerService.send("exe-resultMsg-topic", "*", line);
        }
    }

    @Override
    public boolean preLogSendFilter(String line) {
        return false;
    }

    @Override
    public ExeExecutorExtListener getExeExecutorListener() {
        return null;
    }

    @Override
    public void registryDbService(CalcDbService calcDbService) {
        this.calcDbService = calcDbService;
    }

    @Override
    public void registryResultMsgMQService(ResultMsgProducerService resultMsgProducerService) {
        this.resultMsgProducerService = resultMsgProducerService;
    }
}
